//验证用户是否登录
const jwt = require('jsonwebtoken')

module.exports = (config, app) => {
  return async function authorization (ctx, next) {
    let error = {
      code: 10,
      msg: '请登录！'
    }
    let redisVal = ''
    let { redisKey, keys } = ctx.app.config
    // let token = ctx.cookies.get(
    //   'token', { signed: false }
    // )
    let token = ctx.request.headers.token
   
    if (ctx.path === '/login') {
      await next()
    } else {
      try {
        redisKey = redisKey + token.slice(-43)
        redisVal = await app.redis.get(redisKey)
        if (redisVal === token) {
          jwt.verify(token, keys)
          await next()
        } else {
          ctx.body = error
        }
      } catch (e) {
        ctx.logger.info('redis verify error:'+ e)
        ctx.body = error
      }
    }
  }
}
